package algorithms;

import org.junit.Test;


import java.util.List;

public class A32 {
    public static void main(String[] args) {
        Thread a = new Thread(()->{
            while (true) {
                System.err.println("111");
            }
        });
        a.setDaemon(true);
        a.start();
        Thread c = new Thread(()->{
            while (true) {
                System.err.println("222");
            }
        });
        c.start();
        c.stop();
        System.err.println("333");
    }
    @Test
    public void test() {
        System.err.println(longestValidParentheses("))))())()()(()"));
    }
    public int longestValidParentheses(String s) {
        char[] arr = s.toCharArray();
        int startIndex = 0;
        int leftCount =0;
        int rightCount=0;
        int maxCount = 0;
        for(int i = 0;i < arr.length;i++){
            if(i == startIndex){
                if(arr[i] == ')'){
                    startIndex++;
                    continue;
                }

            }
            if(arr[i]=='('){
                leftCount++;
            }else {
                rightCount++;
            }
            if(rightCount > leftCount){
                maxCount = leftCount*2> maxCount ? 2*leftCount : maxCount;
                startIndex = i+1;
                rightCount = 0;
                leftCount = 0;
            }
            if( i == arr.length - 1){
                int count = leftCount > rightCount ? rightCount : leftCount;
                maxCount = count > maxCount ? 2*count : maxCount;
            }
        }


         startIndex = arr.length - 1;
         leftCount =0;
         rightCount=0;
        int maxCount1 = 0;
        for(int i = arr.length - 1;i >= 0;i--){
            if(i == startIndex){
                if(arr[i] == '('){
                    startIndex--;
                    continue;
                }

            }
            if(arr[i]==')'){
                rightCount++;
            }else {
                leftCount++;
            }
            if(rightCount < leftCount){
                maxCount1 = rightCount*2 > maxCount1 ? 2*rightCount : maxCount1;
                startIndex = i-1;
                rightCount = 0;
                leftCount = 0;
            }
            if(i == 0){
                int count = leftCount > rightCount ? rightCount : leftCount;
                maxCount1 = maxCount1 <  count ? 2* count: maxCount1;

            }
        }

        maxCount = maxCount> maxCount1 ? maxCount1 : maxCount;
        return maxCount;
    }
}
